package com.mediacloud.app.newsmodule.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.google.gson.JsonObject;
import com.jaeger.library.StatusBarUtil;
import com.mediacloud.app.reslib.enums.XKey;
import com.politics.model.PoliticsConstKt;
import com.mediacloud.app.assembly.util.FileUtil;
import com.mediacloud.app.assembly.util.Utility;
import com.mediacloud.app.model.activity.BaseBackActivity;
import com.mediacloud.app.model.interfaces.DataInvokeCallBack;
import com.mediacloud.app.model.news.ArticleListDataWithAdv;
import com.mediacloud.app.model.news.CatalogItem;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.fragment.newslist.NestedNav;
import com.mediacloud.app.newsmodule.fragment.newslist.TableCatalogItemsFragment;
import com.mediacloud.app.newsmodule.model.NavigateListReciver;
import com.mediacloud.app.newsmodule.utils.NavigateDataInvoker;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig.FeatureModule.BigModule;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig.ServerAppConfigInfo.NavigateBarStyle;
import com.mediacloud.app.reslib.enums.Navigate;
import com.tencent.mmkv.MMKV;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * 带搜索页面的Activity
 */
public class SearchNavigateActivity extends BaseBackActivity implements DataInvokeCallBack<NavigateListReciver>
        , View.OnClickListener {

    protected Fragment navigateFragment;
    protected View mLoadingView, mEmptyContent;
    public static final String Catalogs = TableCatalogItemsFragment.Catatlogs;
    CatalogItem catalog;
    protected ArrayList<CatalogItem> catalogs = new ArrayList<CatalogItem>();
    NavigateDataInvoker navigateDatainvoker;
    boolean needLoadSecondBg = false;
    Navigate navigate = null;
    boolean isUriArgs = false;
    boolean showSecondTag = false;
    private ImageView back, logo;
    private View search;
    private View searchBox;
    private String id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setAnd(true);
        mLoadingView = Utility.findViewById(mRootView, R.id.mLoadingView);
        mEmptyContent = Utility.findViewById(mRootView, R.id.mEmptyContent);
        back = findViewById(R.id.mTop_back);
        logo = findViewById(R.id.app_logo);
        search = findViewById(R.id.search_img);
        searchBox = findViewById(R.id.search_box);
        back.setOnClickListener(this);
        searchBox.setOnClickListener(this);
        search.setOnClickListener(this);
        loadLogo();
        //		initNavigateChild();
        String title = "";
        if (getIntent().getData() != null) {
            try {
                title = getIntent().getData().getQueryParameter("title");
                id = getIntent().getData().getQueryParameter("id");
                String navname = getIntent().getData().getQueryParameter("navname");
                showSecondTag = Boolean.valueOf(getIntent().getData().getQueryParameter("showSecond"));
                catalog = new CatalogItem();
                catalog.setCatalog_type(String.valueOf(getIntent().getData().getQueryParameter("type")));
                catalog.setCatid(id);
                catalog.setCatname(TextUtils.isEmpty(navname) ? title : navname);
                navigate = new Navigate();
                navigate.setCategory(catalog.getCatalog_type());
                navigate.name = navigate.sname = TextUtils.isEmpty(navname) ? title : navname;
                navigate.id = id;
                catalog.setNavigate(navigate);
                isUriArgs = true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            catalog = getIntent().getParcelableExtra(Catalogs);
            showSecondTag = getIntent().getBooleanExtra("showSecondTag", false);
            navigate = getIntent().getParcelableExtra("navigate");
            catalog.setNavigate(navigate);
        }
        if (catalog != null) {
            navigateDatainvoker = new NavigateDataInvoker(this);
            navigateDatainvoker.invokeChildNavigate(catalog.getCatid(), this, isUriArgs);
        }
    }

    private void loadLogo() {
        try {
            Class<?> aClass = Class.forName("com.mediacloud.app.appfactory.activity.home.HomeActivityBase");
            Field[] fields = aClass.getFields();
            int index = 0;
            for (Field f :
                    fields) {
                if (f.getName().equals("pageIndex")) {
                    f.setAccessible(true);//打开私有访问
                    //获取属性值
                    index = (int) f.get(null);
                    break;
                }
            }
            String configs = MMKV.defaultMMKV().getString(XKey.CACHE_CONFIGURATION,null);
            JSONObject parse = JSONObject.parseObject(configs);
            JSONObject data = parse.getJSONObject("data");
            JSONArray navigate = data.getJSONArray("navigate");
            JSONObject jsonObject = navigate.getJSONObject(index);
            JSONArray left = jsonObject.getJSONObject("top_bar").getJSONArray("left");
            if (left != null && left.size() > 0) {
                for (int i = 0; i < left.size(); i++) {
                    JSONObject leftItem = left.getJSONObject(i);
                    String type = leftItem.getString("type");
                    if (type != null && type.equals("logo")) {
                        String logoUrl = leftItem.getString("logo");
                        if (logoUrl != null && !logoUrl.equals("")) {
                            Glide.with(this).load(logoUrl).into(logo);
                        }
                        break;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void renderTitleBarIconColor() {
        super.renderTitleBarIconColor();
    }

    @Override
    public int getLayoutResID() {
        return R.layout.aappfactory_navigate_activity_search;
    }

    protected void initNavigateChild() {
        navigateFragment = new NestedNav();
        Bundle arguments = new Bundle();
        if (showSecondTag) {
            arguments.putParcelableArrayList(Catalogs, catalogs);
        } else {
            //bug  Android端，组件绑定导航，关闭二级导航，会重复显示绑定的导航  https://zentao.chinamcloud.com/zentao/bug-view-21741.html
            ArrayList<CatalogItem> emptyCatalogItem = new ArrayList<CatalogItem>();
            arguments.putParcelableArrayList(Catalogs, emptyCatalogItem);
        }
        arguments.putSerializable("navigate", navigate);
        arguments.putBoolean(Intent.ACTION_INSERT, true);
        navigateFragment.setArguments(arguments);//提前设置  不然下面去设置会覆盖值
        if (catalogs.size() == 1) {
            //只有一个 并且 导航 是链接等这几类的情况 下才需要加载第二个背景图
            String type = catalogs.get(0).getCatalog_type();
            if (BigModule.Link.equals(type) || BigModule.H5Broke.equals(type) || BigModule.ScoreMall.equals(type)) {
                needLoadSecondBg = true;
                loadSecondSkinBg();
            }
            //不取二级导航  直接加载
			/*Fragment fragment= AppModuleUtils.getViewContentFragment(this,catalog);
			if(fragment!=null)
			{
				navigateFragment=fragment;
			}*/
        }
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.navigateContent, navigateFragment);
        transaction.show(navigateFragment);
        transaction.commitNowAllowingStateLoss();
        mLoadingView.setVisibility(View.GONE);
    }
    @Override
    protected boolean needLoadTopSecondBgSkin() {
        return needLoadSecondBg && super.subClassgetNeedTopSecondBgSkin();//"1".equals(getResources().getString(R.string.need_load_second_topskin));
    }

    @Override
    protected NavigateBarStyle getNewsDetailNavigateBarStyle() {
        if (needLoadSecondBg) {
            return AppFactoryGlobalConfig.getAppServerConfigInfo(this).getLinkNewsBar();
        }
        return null;
    }

    protected void setNewsTitle() {
        if (needLoadTopSecondBgSkin()) {
            return;
        }
        if (!TextUtils.isEmpty(getServerConfigTitle())) {
            setTitle(getServerConfigTitle());
        } else if (isNavigateTitle() && catalog != null) {
            setTitle(catalog.getCatname());
        } else {
            String title = getIntent().getStringExtra("title");
            if (!TextUtils.isEmpty(title))
                setTitle(title);
        }
    }

    @Override
    public void finish() {
        super.finish();
        if (navigateDatainvoker != null)
            navigateDatainvoker.destory();
        navigateDatainvoker = null;
        if (catalogs != null)
            catalogs.clear();
        catalogs = null;
    }

    @Override
    public void success(NavigateListReciver data) {
        if (isUriArgs) {
            if (data.catalogs.size() > 0) {
                CatalogItem removed = data.catalogs.remove(0);
                String title = removed.getCatname();
                catalog = removed;
                navigate = catalog.getNavigate();
                //这去单独判断一下是不是对象问题 如果是 并且要先打开选择页面 那么就把取到的里面的导航列表类型设置成问政对象列表的类型
                if (BigModule.OBJECT_POLITICS_NAV.equals(catalog.getCatalog_type()) || BigModule.Publish_Politics.equals(catalog.getCatalog_type())) {
                    //问政的时候是不显示二级导航的
                    showSecondTag = false;
                    if (catalog.is_select_politics_spider == 1) {
                        catalog.setCatalog_type(BigModule.Politics_Choose_Object);
                        navigate.setCategory(BigModule.Politics_Choose_Object);
                        if (catalog.getPolitics_type() == PoliticsConstKt.TYPE_SHUJI_XINXIANG || catalog.getPolitics_type() == PoliticsConstKt.TYPE_ZHUANYUAN_XINXIANG) {
                            if (catalog.getPolitics_type() == PoliticsConstKt.TYPE_SHUJI_XINXIANG) {
                                setTitle("给书记写信");
                            } else {
                                setTitle("给专员写信");
                            }
                        } else {
                            setTitle(getResources().getString(R.string.politics_objects, catalog.getPolitics_identification()));
                        }
                    } else {
                        if (catalog.getPolitics_type() == PoliticsConstKt.TYPE_SHUJI_XINXIANG || catalog.getPolitics_type() == PoliticsConstKt.TYPE_ZHUANYUAN_XINXIANG) {
                            if (catalog.getPolitics_type() == PoliticsConstKt.TYPE_SHUJI_XINXIANG) {
                                setTitle("给书记写信");
                            } else {
                                setTitle("给专员写信");
                            }
                        } else {
                            setTitle(getResources().getString(R.string.iwant_ask_politic, catalog.getPolitics_identification()));
                        }
                        if (mTitlebar_name != null) {
                            mTitlebar_name.getPaint().setFakeBoldText(false);
                            mTitlebar_name.setIncludeFontPadding(false);
                            mTitlebar_name.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelSize(R.dimen.dimen20sp));
                        }
                    }
                    //全部把导航清了 就只显示一个叫他选择对象的那个列表
                    data.catalogs.clear();
                    catalogs.clear();
                    data.catalogs.add(catalog);
                } else {
                    if (TextUtils.isEmpty(title) == false) {
                        catalog.setCatname(title);
                        navigate.setName(title);
                        navigate.setSname(title);
                        navigate.setSecond_navigate(removed.getNavigate().getSecond_navigate());
                    }
                    if (catalog.getIs_second_navigate() == 0 || !showSecondTag) {
                        data.catalogs.clear();
                        catalogs.clear();
                        data.catalogs.add(catalog);
                    }
                }

            }
        }
        catalogs.addAll(data.catalogs);
        initNavigateChild();
    }


    public void refreshNavBarColor(int color) {
        mTitileBar.setBackgroundColor(color);
//		refreshStatusBarColor();
        StatusBarUtil.setColorNoTranslucent(this, color);
    }


    @Override
    public void fault(Object data) {
        initNavigateChild();
    }

    /**
     * 主要是导航里头有全屏的那种东西的
     *
     * @return
     */
    @Override
    public int getStatusBarColor() {
        final int flag = WindowManager.LayoutParams.FLAG_FULLSCREEN;
        if ((getWindow().getAttributes().flags & flag) == flag) {
            return Color.TRANSPARENT;
        }
        return super.getStatusBarColor();
    }

    //设置当前栏目的Id
    private static String catalogId = null;


    public static void setCatalogId(int i) {
        switch (i) {
            case 0:
                catalogId = "1580,10";
                break;
            case 1:
                catalogId = "1581,906";
                break;
            case 2:
                catalogId = "1582,10";
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        setAnd(false);
        catalogId = null;
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.mTop_back) {
            finish();
        } else if (id == R.id.search_box || id == R.id.search_img) {
            try {
                //反射调用搜索Activity
                Class<?> aClass = Class.forName("com.mediacloud.app.appfactory.activity.search.SearchActivity");
                Method[] methods = aClass.getMethods();
                for (Method method : methods
                ) {
                    if (method.getName().equals("start")
                    ) {
                        method.invoke(null, SearchNavigateActivity.this, getCatId());
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void setAnd(boolean b) {
        ArticleListDataWithAdv.setSearchActivityIsShow(b);
    }

    @Override
    protected void onResume() {
        super.onResume();
        setAnd(true);
    }

    private String getCatId() {
        String res = ArticleListDataWithAdv.getCatidt();
        if (res != null) {
            if (res.equals("1580") || res.equals("1581") || res.equals("1582")) {
                if (catalogId != null) {
                    res = catalogId;
                }
            }
        }
        return res;
    }

}